<template>
  <div class="account-box">
    <div class="toggle">
      <a @click="isMsgLogin = false" href="javascript:;" v-if="isMsgLogin">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a @click="isMsgLogin = true" href="javascript:;" v-else>
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <Form
      ref="formValidate"
      class="form"
      :validation-schema="Schema"
      v-slot="{ errors }"
      autocomplete="off"
    >
      <template v-if="!isMsgLogin">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field
              v-model="form.account"
              type="text"
              name="account"
              placeholder="请输入用户名或手机号"
              :class="{ error: errors.account }"
            />
          </div>
          <div class="error">
            <i class="iconfont icon-warning" v-if="errors.account" />{{
              errors.account
            }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <Field
              type="password"
              v-model="form.password"
              name="password"
              placeholder="请输入密码"
              :class="{ error: errors.password }"
            />
          </div>
          <div class="error">
            <i class="iconfont icon-warning" v-if="errors.password" />{{
              errors.password
            }}
          </div>
        </div>
      </template>
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field
              type="text"
              v-model="form.mobile"
              name="mobile"
              placeholder="请输入手机号"
              :class="{ error: errors.mobile }"
            />
          </div>
          <!-- 错误信息 -->
          <div class="error">
            <i class="iconfont icon-warning" v-if="errors.mobile" />{{
              errors.mobile
            }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <Field
              type="password"
              v-model="form.code"
              name="code"
              placeholder="请输入验证码"
              :class="{ error: errors.code }"
            />
            <span @click="sendMsg()" class="code">
              {{ time === 0 ? '发送验证码' : `${time}秒后发送` }}
            </span>
          </div>
          <!-- 错误信息 -->
          <div class="error">
            <i class="iconfont icon-warning" v-if="errors.code" />{{
              errors.code
            }}
          </div>
        </div>
      </template>
      <div class="form-item">
        <div class="agree">
          <Field as="XtxCheckbox" name="isAgree" v-model="form.isAgree" />
          <span>我已同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <div class="error">
          <i class="iconfont icon-warning" v-if="errors.isAgree" />{{
            errors.isAgree
          }}
        </div>
      </div>
      <a @click="login" href="javascript:;" class="btn">登录</a>
    </Form>
    <div class="action">
      <!-- qq登录 -->
      <a
        href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback"
      >
        <img
          src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png"
          alt=""
        />
      </a>

      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>

<script>
import { userAccountLogin, userMobileLoginMsg } from '@/api/user'
import { getCurrentInstance, reactive, ref, watch, onUnmounted } from 'vue'
import { Form, Field } from 'vee-validate'
import veeSchema from '@/vender/vee-validate-schema.js'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { useIntervalFn } from '@vueuse/core'
// import QC from 'qc'

// import Message from '@/components/library/Message.js'
export default {
  name: 'LoginForm',
  components: {
    Form,
    Field
  },
  setup() {
    // 使用store
    const store = useStore()
    // 使用路由
    const route = useRoute()
    const router = useRouter()
    // setup中getCurrentInstance() 获取当前组件实例proxy
    const { proxy } = getCurrentInstance()
    // 控制短信登录切换的
    const isMsgLogin = ref(false)
    // 表单实例
    const formValidate = ref(null)
    // 短信倒计时
    const time = ref(0)
    // 表单对象数据
    const form = reactive({
      isAgree: true,
      account: null,
      password: null,
      mobile: null,
      code: null
    })
    // 校验规则对象
    const Schema = {
      account: veeSchema.account,
      password: veeSchema.password,
      mobile: veeSchema.mobile,
      code: veeSchema.code,
      isAgree: veeSchema.isAgree
    }
    //  切换登录清空表单
    watch(isMsgLogin, () => {
      form.isAgree = true
      form.account = null
      form.password = null
      form.mobile = null
      form.code = null
    })
    // 登录
    const login = () => {
      // zhousg 123456
      // Form组件提供了一个validate函数作为整体表单校验
      formValidate.value.validate().then(async (valid) => {
        // proxy.$message('success', '登录成功')
        if (valid) {
          try {
            let data = null
            if (isMsgLogin.value) {
              // 手机号登录
              //
              const { mobile, code } = form
              data = await userMobileLoginMsg({ mobile, code })
            } else {
              // 账号登录
              const { account, password } = form
              data = await userAccountLogin({ account, password })
              // .catch((e) => {
              //   proxy.$message('error', e.response.data.message)
              // })
            }
            const { id, account, avatar, mobile, nickname, token } = data.result
            // 存储用户数据
            store.commit('user/setUser', {
              id,
              account,
              avatar,
              mobile,
              nickname,
              token
            })
            // 合并购物车 跳转到token消逝的页面或首页
            store.dispatch('cart/metgeCart').then(() => {
              router.push(route.query.redirectUrl || '/')
              proxy.$message('success', '登录成功')
            })
          } catch (error) {
            // 用户不存在
            if (error.response.data) {
              proxy.$message('error', error.response.data.message)
            }
          }
        }
      })
    }

    // 短信发送开启定时器
    const { pause, resume } = useIntervalFn(
      () => {
        time.value--
        if (time.value <= 0) {
          pause()
        }
      },
      1000,
      false
    )
    // 销毁时关闭定时器
    onUnmounted(() => {
      pause()
    })
    // 点击发送验证码
    const sendMsg = () => {
      const valid = veeSchema.mobile(form.mobile)
      if (valid === true) {
        if (time.value === 0) {
          // 通过
          userMobileLoginMsg(form.mobile)
            .then((data) => {
              proxy.$message('success', '消息已经发送')
              time.value = 60
              resume()
            })
            .catch((e) => {
              proxy.$message('error', e.response.data.message)
            })
        }
      } else {
        // 失败，触发vee的错误函数显示错误信息setFieldError字段
        formValidate.value.setFieldError('mobile', valid)
      }
    }
    // // 初始化qq登录按钮
    // onMounted(() => {
    //   QC.Login({ btnId: 'qqLoginBtn' })
    // })
    return { isMsgLogin, form, Schema, formValidate, login, sendMsg, time }
  }
}
</script>

<style lang="less" scoped>
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,
          &:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
